package com.project.filter;

import com.alibaba.fastjson.JSON;
import com.project.baseInfo.model.LoginUserInfo;
import com.project.baseInfo.model.User;
import com.project.constants.SessionConstants;
import com.project.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    /*@Autowired
    private RedisCache redisCache;*/

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse =(HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();

        /*
         * Filter优先于spring加载的bean，所以调用以下两行来获取spring中redis的bean
         */
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
        RedisCache redisCache = (RedisCache) webApplicationContext.getBean("redisCache");

        String requestUrl = httpRequest.getRequestURI();//获取请求的url
        String token = httpRequest.getParameter("token");//获取请求来的token
        String jumpLogin = "/login/jumpLogin.do";

        // login.jsp页面无需过滤(根据自己项目的要求来)
        if(requestUrl.endsWith("login.do")||requestUrl.endsWith("jumpLogin.do")||requestUrl.endsWith("registerUser.do")) {//注意：登录页面千万不能过滤  不然过滤器就。。。。。自行调试不要偷懒！这样记忆深刻
            arg2.doFilter(request, response);
            return;
        } else {//如果不是login.jsp进行过滤
            if (StringUtils.isEmpty(token)) {
                // 跳转到登陆页面
                session.removeAttribute(SessionConstants.USER);
                httpResponse.setHeader("sessionstatus","timeout");
                httpResponse.setStatus(403);
                httpRequest.getSession().setAttribute("msg", "您的会话已过期,请重新登录");
                httpResponse.sendRedirect(jumpLogin);
                //httpRequest.getRequestDispatcher("jumpLogin.do").forward(request, httpResponse);
                return;
            } else {
                String userJson = (String)redisCache.getObject(token);
                if (StringUtils.isEmpty(userJson)){
                    // 登录信息失效
                    session.removeAttribute(SessionConstants.USER);
                    httpResponse.setHeader("sessionstatus","timeout");
                    httpResponse.setStatus(403);
                    httpRequest.getSession().setAttribute("msg", "您的会话已过期,请重新登录");
                    httpResponse.sendRedirect(jumpLogin);
                    return;
                }
                LoginUserInfo loginUserInfo = JSON.parseObject(userJson, LoginUserInfo.class);
                if (null == loginUserInfo){
                    // 登录信息失效
                    session.removeAttribute(SessionConstants.USER);
                    httpResponse.setHeader("sessionstatus","timeout");
                    httpResponse.setStatus(403);
                    httpRequest.getSession().setAttribute("msg", "您的会话已过期,请重新登录");
                    httpResponse.sendRedirect(jumpLogin);
                    return;
                }else {
                    String newToken = (String) redisCache.getObject(loginUserInfo.getId());
                    if (StringUtils.isEmpty(newToken)||!newToken.equals(token)){
                        // 跳转到登陆页面
                        session.removeAttribute(SessionConstants.USER);
                        httpResponse.setHeader("sessionstatus","timeout");
                        httpResponse.setStatus(403);
                        httpRequest.getSession().setAttribute("msg", "用户已在别处登陆，请重新登陆");
                        httpResponse.sendRedirect(jumpLogin);
                        redisCache.removeObject(token);
                        return;
                    }else {
                        // 已经登陆,继续此次请求
                        httpRequest.getSession().setAttribute("loginUserInfo", JSON.toJSONString(loginUserInfo));
                        arg2.doFilter(request, response);
                    }
                }
            }
        }
    }

    public void destroy() {

    }
}
